package com.toman.ui.operation.enterprise.preheat;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Adpter.StateSelectExpandableListViewAdapter;
import com.toman.Adpter.StateSelect_adpter;
import com.toman.Entity.StateSelect_Entity;
import com.toman.Interfaces.BaseUrl;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.StatusBarUtils;
import com.toman.Util.ToastUtil;
import com.toman.toolbar.ToolBarActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import okhttp3.Request;
import okhttp3.Response;

public class MutiOpenActivity extends ToolBarActivity implements StateSelect_adpter.SignupListClickListener, Toolbar.OnMenuItemClickListener {

    MyApplication myApplication;
    @BindView(R.id.tv_all)
    TextView tvAll;
    @BindView(R.id.tv_none)
    TextView tvNone;
    @BindView(R.id.tv_contrary)
    TextView tvContrary;

    /**
     * 每个分组的名字的集合
     */
    private ArrayList<String> arrayList = new ArrayList<String>();

    /**
     * 所有分组的所有子项的 GridView 数据集合
     */
    private ArrayList<ArrayList<StateSelect_Entity>> array = new ArrayList<ArrayList<StateSelect_Entity>>();

    ExpandableListView mState_Expandable;
    BGARefreshLayout mState_refresh;

    StateSelectExpandableListViewAdapter stateAdpter;
    Integer id;
    int type;
    JSONObject jsonObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_muti_open);
        ButterKnife.bind(this);
        initToolBar("选择产线", getResources().getColor(R.color.c1));
        initHandler();
        initView();
    }


    /*
        初始化控件
     */
    public void initView() {
        myApplication = (MyApplication) getApplication();
        id = getIntent().getIntExtra("id", -1);
        type = getIntent().getIntExtra("type", 0);

        mState_refresh = (BGARefreshLayout) findViewById(R.id.mState_refresh);
        mState_Expandable = (ExpandableListView) findViewById(R.id.mState_Expandable);
        // 隐藏分组指示器
        mState_Expandable.setGroupIndicator(null);

        if (myApplication.getSp().getString("token", "").equals("toman")) {
            StatusBarUtils.setWindowStatusBarColor(this, R.color.loginbg);

        } else if (myApplication.getSp().getString("token", "").equals("operater")) {
            StatusBarUtils.setWindowStatusBarColor(this, R.color.myBgn);

        } else if (myApplication.getSp().getString("token", "").equals("company")) {
            StatusBarUtils.setWindowStatusBarColor(this, R.color.c1);
        }

        stateAdpter = new StateSelectExpandableListViewAdapter(this, arrayList, array, myApplication, mHandler);
        mState_Expandable.setAdapter(stateAdpter);
        mState_Expandable.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                StateSelect_Entity entity = array.get(groupPosition).get(childPosition);
                ToastUtil.makeText(getApplicationContext(), entity.getName());
                ToastUtil.print(entity.getName());
                ToastUtil.print("ok");

                return true;
            }
        });



        if (type == 0) {
            user();
        } else {
        }

        mState_refresh.setIsShowLoadingMoreView(true);
        mState_refresh.setRefreshViewHolder(new BGANormalRefreshViewHolder(MyApplication.getInstance(), true));

        mState_refresh.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                if (true) {
                    // 如果网络可用，则加载网络数据
                    if (type == 0) {
                        user();
                    } else {

                    }
                } else {
                    // 网络不可用，结束下拉刷新
                    mState_refresh.endRefreshing();
                }
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                return false;
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_save, menu);
        toolbar.setOnMenuItemClickListener(this);

        return true;
    }

    /*
        产线列表 > 设备状态
    */
    public void user() {
        String token = myApplication.getSp().getString("tokenId", "");
        OkHttpUtils
                .post(BaseUrl.getPreheatList)
                .params("token", token)
                .params("customer_id", id.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "设备状态列表: " + result);
                        arrayList.clear();
                        array.clear();
                        try {
                            JSONObject js = new JSONObject(result);
                            jsonObject = js;
                            int code = js.getInt("code");
                            if (code == 1) {
                                JSONArray data = js.getJSONArray("data");
                                //  JSONArray rows = data.getJSONArray("rows");
                                for (int i = 0; i < data.length(); i++) {
                                    JSONObject ji = data.getJSONObject(i);
                                    JSONArray le = ji.getJSONArray("beltline");
                                    String name = ji.getString("workshop_name");
                                    arrayList.add(name);

                                    ArrayList<StateSelect_Entity> arrayList1 = new ArrayList<StateSelect_Entity>();

                                    for (int k = 0; k < le.length(); k++) {
                                        JSONObject jas = le.getJSONObject(k);
                                        int beltline_id = jas.getInt("id");

                                        String beltline_name = jas.getString("beltline_name");
                                        String beltline_status = jas.getString("beltline_status");
                                        StateSelect_Entity en1;
                                        if (jas.getString("preheat_state").equals("2")) {
                                            en1 = new StateSelect_Entity(beltline_id, beltline_name, beltline_status, true);
                                        } else {
                                            en1 = new StateSelect_Entity(beltline_id, beltline_name, beltline_status, false);

                                        }
                                        arrayList1.add(en1);
                                    }
                                    array.add(arrayList1);
                                }

                                for (int i = 0; i < array.size(); i++) {
                                    mState_Expandable.expandGroup(i, true);
                                }

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        stateAdpter.notifyDataSetChanged();
                        mState_refresh.endRefreshing();
                        setTvTitle("选择产线" + "(" + "已选择" + stateAdpter.getSelectCount() + "项)");

                    }
                });
    }


    @OnClick({R.id.tv_all, R.id.tv_none, R.id.tv_contrary})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_all:
                stateAdpter.selectAll();
                setTitle("");
                break;
            case R.id.tv_none:
                stateAdpter.selectNone();

                break;
            case R.id.tv_contrary:
                stateAdpter.selectContrary();

                break;
        }
        setTvTitle("选择产线" + "(" + "已选择" + stateAdpter.getSelectCount() + "项)");
    }

    @Override
    public void signupClick() {
        setTvTitle("选择产线" + "(" + "已选择" + stateAdpter.getSelectCount() + "项)");

    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_save:
                save();
                ToastUtil.print(stateAdpter.getSelectResult());

                break;
        }
        return false;
    }


    public void save() {
        String token = myApplication.getSp().getString("tokenId", "");
        OkHttpUtils
                .post(BaseUrl.preheat_edit)
                .params("token", token)
                .params("preheat_ids", stateAdpter.getSelectResult())
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "修改选中列表: " + result);
                        try {
                            JSONObject js = new JSONObject(result);
                            int code = js.getInt("code");
                            if (code == 1) {


                                Toast.makeText(getApplicationContext(), "" + js.getString("msg"), Toast.LENGTH_SHORT).show();
                                finish();
                                //customerManager();

                            } else {
                                Toast.makeText(getApplicationContext(), "" + js.getString("msg"), Toast.LENGTH_SHORT).show();


                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void initHandler() {
        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {

                    case 1:
                        setTvTitle("选择产线" + "(" + "已选择" + stateAdpter.getSelectCount() + "项)");

                        break;
                    default:
                        break;
                }
            }
        };
    }
}
